import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import "./ScheduleAdd.css";

export default function ScheduleAdd() {
  const [movieId, setMovieId] = useState("");
  const [startTime, setStartTime] = useState("");
  const [price, setPrice] = useState("");
  const [movies, setMovies] = useState([]);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [loadingMovies, setLoadingMovies] = useState(true);
  const navigate = useNavigate();

  // 获取电影列表，用于验证movie_id是否存在
  useEffect(() => {
    fetch("http://localhost:8080/api/movies")
      .then((response) => {
        if (!response.ok) {
          throw new Error("获取电影列表失败");
        }
        return response.json();
      })
      .then((data) => {
        setMovies(data);
        setLoadingMovies(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoadingMovies(false);
      });
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);

    // 简单验证
    if (!movieId || isNaN(movieId) || movieId <= 0) {
      setError("请输入有效的电影ID");
      return;
    }

    // 验证电影ID是否存在
    const movieExists = movies.some(
      (movie) => movie.id === parseInt(movieId, 10)
    );
    if (!movieExists) {
      setError("指定的电影ID不存在，请检查后重试");
      return;
    }

    if (!startTime) {
      setError("请选择开始时间");
      return;
    }

    if (!price || isNaN(price) || price <= 0) {
      setError("请输入有效的价格");
      return;
    }

    try {
      const response = await fetch("http://localhost:8080/api/schedules", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          movie_id: parseInt(movieId, 10),
          start_time: startTime,
          price: parseFloat(price),
        }),
      });

      if (!response.ok) {
        throw new Error("添加排片失败");
      }

      const data = await response.json();
      setSuccess("排片添加成功！");
      // 清空表单
      setMovieId("");
      setStartTime("");
      setPrice("");

      // 3秒后跳转到电影列表
      setTimeout(() => {
        navigate("/movies");
      }, 3000);
    } catch (error) {
      setError(error.message);
    }
  };

  return (
    <div className="schedule-add-container">
      <h1>添加排片</h1>
      <div className="schedule-form-container">
        <form className="schedule-form" onSubmit={handleSubmit}>
          {error && <div className="error-message">{error}</div>}
          {success && <div className="success-message">{success}</div>}

          <div className="form-group">
            <label htmlFor="movieId">电影ID</label>
            <input
              type="number"
              id="movieId"
              value={movieId}
              onChange={(e) => setMovieId(e.target.value)}
              placeholder="请输入电影ID"
              min="1"
            />
            {!loadingMovies && (
              <div className="movie-list">
                <p>可选电影:</p>
                <ul>
                  {movies.map((movie) => (
                    <li key={movie.id}>
                      ID: {movie.id}, 标题: {movie.title}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>

          <div className="form-group">
            <label htmlFor="startTime">开始时间</label>
            <input
              type="datetime-local"
              id="startTime"
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
            />
          </div>

          <div className="form-group">
            <label htmlFor="price">票价 (元)</label>
            <input
              type="number"
              id="price"
              value={price}
              onChange={(e) => setPrice(e.target.value)}
              placeholder="请输入票价"
              min="0.1"
              step="0.1"
            />
          </div>

          <div className="form-actions">
            <button type="submit">提交</button>
            <button type="button" onClick={() => navigate("/movies")}>
              取消
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
